﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CustomerMgr.Data.Models;

namespace CustomerMgr.Data
{
    public class CustomerFactory
    {
        public static List<Customer> SelectAll()
        {
            try
            {
                var db = new ordermanagerContext();
                return db.Customers.ToList();
            }
            catch
            {
                return null;
            }
        }
        public static Customer SelectOne(int customerId)
        {
            try
            {
                var db = new ordermanagerContext();
                return db.Customers.FirstOrDefault(s => s.Id.Equals(customerId));
            }
            catch
            {
                return null;
            }
        }
        public List<Customer> Search(string keyword)
        {
            try
            {
                var db = new ordermanagerContext();
                return db.Customers.Where(s => s.Name.ToLower().Contains(keyword.ToLower())).ToList();
            }
            catch
            {
                return null;
            }
        }
        public static Customer Insert(Customer customer)
        {
            try
            {
                var db = new ordermanagerContext();
                db.Customers.Add(customer);
                db.SaveChanges();
                return customer;
            }
            catch
            {
                return null;
            }
        }
        public static bool Update(Customer customer)
        {
            try
            {
                var db = new ordermanagerContext();
                var cus = (from i in db.Customers
                           where i.Id == customer.Id
                           select i).First();
                cus.Name = customer.Name;
                cus.Description = customer.Description;
                db.SaveChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }
        public static bool Delete(Customer customer)
        {
            try
            {
                var db = new ordermanagerContext();
                var cus = (from i in db.Customers
                           where i.Id == customer.Id
                           select i).First();
                db.Customers.Remove(cus);
                db.SaveChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}
